/**
 * HTMLUtils.java 12.05.2006 17:56:47 dicr
 */
package org.dicr.util.text;

/**
 * @author <A href='http://dicr.org'>Igor A Tarasov</A>
 * @version 060512
 */
public class HtmlUtils {
	/**
     * Convert object to string and escape html entities (replace [<B>&amp;</B> <B>&lt;</B> <B>&gt;</B> <B>&quot;</B> <B>&apos;</B>]
     * chars with [<B>&amp;amp;</B> <B>&amp;lt;</B> <B>&amp;gt;</B> <B>&amp;quot;</B> <B>&amp;apos;</B>] strings).
     * 
     * @param obj object to escape
     * @return obj.toString with escaped special html chars or '' if obj == null.
     */
	public static String escape(Object obj) {
		char[] content = obj == null ? new char[0] : obj.toString().toCharArray();
		StringBuffer sb = new StringBuffer();
		for (int i=0; i<content.length; i++) {
			char c = content[i];
			switch (c) {
				case '<': 
					sb.append("&lt;");
					break;
				case '>':
					sb.append("&gt;");
					break;
				case '&':
					sb.append("&amp;");
					break;
				case '"':
					sb.append("&quot;");
					break;
				case '\'':
					sb.append("&apos;");
					break;
				default:
					sb.append(c);
					break;
			}
		}
		return sb.toString();
	}

	/**
     * Trim spaces in string. Return null if string == ""
     * 
     * @param str string to trim or null
     * @return trimmed string or null if emptys
     */
	public static String trim(String str) {
		if (str == null) return null;
		String s = str.trim();
		return (s.length() > 0) ? s : null;
	}
}
